﻿using System;

public class Client
{
	private static byte[] m_DataBuffer = new byte[1024];
	static void Main(string[] args)
	{
		IPAddress ip = IPAddress.Loopback;
		Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

		try
		{
			clientSocket.Connect(new IPEndPoint(ip, 8099));
			Console.WriteLine("连接服务器成功");
		}
		catch (Exception ex)
		{
			Console.WriteLine("连接服务器失败，按回车退出");
			Console.WriteLine(ex.Message);
			return;
		}

		Thread receive = new Thread(ReceiveMsg);
		receive.start();

		Thread send = new Thread(SendMsg);
		send.start();
		
		//通过clientSocket接收数据
		int receiveLength = clientSocket.Receive(m_DataBuffer);
		Console.WriteLine("接受服务器消息:{0}", Encoding.UTF8.GetString(m_DataBuffer, 0, receiveLength));
		//通过clientSocket发送数据
		for(int i = 0; i < 10; i++)
		{
			try
			{
				Thread.Sleep(1000);
				string sendMessage = string.Format("{0} {1}", "Server 你好!", DateTime.Now.ToString());
				clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));
				Console.WriteLine("向服务器发送消息:{0}", sendMessage);
			}
			catch
			{
				clientSocket.Shutdown(SocketShutdown.Both);
				clientSocket.Close();
				break;
			}
		}
		Console.WriteLine("发送完毕，按回车退出");
		Console.Read();
	}

	private static void ReceiveMsg()
	{
		while (true)
		{
			try
			{
				int receiveLength = clientSocket.Receive(m_DataBuffer);
				Console.WriteLine("服务器消息：{0}", Encoding.UTF8.GetString(m_DataBuffer, 0, receiveLength));
			}
			catch
			{
				Console.WriteLine("Error");
			}
		}
	}

	private static void SendMsg()
	{
		while (true)
		{
			try
			{
				string msg = Console.ReadLine();
				clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));
				Console.WriteLine("向服务器发送消息:{0}", sendMessage);
			}
			catch
			{
				clientSocket.Shutdown(SocketShutdown.Both);
				clientSocket.Close();
				break;
			}
		}
	}
}
